const gulp = require('gulp')
const rollup = require('rollup')
const uglify = require('gulp-uglify')
const rename = require('gulp-rename')
const sass = require('gulp-sass')

const rollupInput = require('./build/rollup/input')
const rollupOutput = require('./build/rollup/output')

/**
 * build umd bundle
 */
gulp.task('rollup-umd', function () {
  return rollup.rollup(rollupInput('umd'))
    .then(function (bundle) {
      bundle.write(rollupOutput('umd'))
    })
})

/**
 * build cjs module
 */
gulp.task('rollup-cjs', function () {
  return rollup.rollup(rollupInput('cjs'))
    .then(function (bundle) {
      bundle.write(rollupOutput('cjs'))
    })
})

/**
 * watch rollup-umd task
 */
gulp.task('rollup:watch', function () {
  gulp.watch('src/js/**/*.js', ['rollup-umd'])
  process.on('SIGINT', function () {
    process.exit()
  });
})

/**
 * minify dist
 */
gulp.task('compress', function () {
  const compressUmd = gulp.src('dist/umd/viil.js')
    .pipe(uglify())
    .pipe(rename({ extname: '.min.js' }))
    .pipe(gulp.dest('dist/umd'))

  const compressCjs = gulp.src('dist/cjs/viil.js')
    .pipe(uglify())
    .pipe(rename({ extname: '.min.js' }))
    .pipe(gulp.dest('dist/cjs'))
  return Promise.all([compressUmd, compressCjs])
})

/**
 * sass compile
 */
gulp.task('sass', function () {
  return gulp.src('src/css/viil.scss')
    .pipe(sass({includePaths: ['./']}).on('error', sass.logError))
    .pipe(gulp.dest('dist/css'))
})

/**
 * watch sass compile
 */
gulp.task('sass:watch', function () {
  gulp.watch('src/css/**/*.scss', ['sass'])
})
